package org.fujene.communicate.node;

import java.net.UnknownHostException;

import org.fujene.constants.Constants;
import org.msgpack.rpc.Client;

@Deprecated
public final class BoldNode implements Comparable<BoldNode> {
	private String addr;
	private long hash;
	private boolean indexable;
	public Object indexableSwitch;
	private boolean isDead;
	private Client client;

	@Override
	public int compareTo(BoldNode arg) {
		if(this.hash == arg.hash) return 0;
		if (this.hash >= 0) {
			if (arg.hash < 0)
				return -1; // greater than arg
			else
				return (this.hash > arg.hash ? 1 : -1);
		} else {
			if (arg.hash >= 0)
				return 1; // less than arg
			else
				return (this.hash > arg.hash ? 1 : -1);
		}
	}

	public boolean equals(Object arg) {
		if (arg instanceof BoldNode) {
			return ((BoldNode) arg).hash == this.hash;
		}

		return false;
	}

	public BoldNode(String addr, long hash) {
		this.addr = addr;
		this.hash = hash;
		this.isDead = false;
		this.indexable = false;
		this.indexableSwitch = new Object();
	}

	public String getAddr() {
		return addr;
	}

	public long getHash() {
		return hash;
	}

	public boolean isDead() {
		return isDead;
	}

	public void indexable() {
		this.indexable = true;
		synchronized(this.indexableSwitch){
			this.indexableSwitch.notifyAll();
		}
	}
	
	public void notIndexable() {
		this.indexable = false;
	}
	
	public boolean isIndexable() {
		return indexable;
	}

	public void setDead() {
		this.isDead = true;
	}
	
	public Client openClient() throws UnknownHostException {
		if(addr == null) return null;
		client = new Client(addr, Constants.PEER_PORT);
		return client;
	}
	
	public Client client() {
		return client;
	}
	
	public void setTimeout(int timeout) {
		client.setRequestTimeout(timeout);
	}
	
	public void closeClient() {
		if(client != null)
			client.close();
	}

	@Override
	public String toString() {
		return String.format("<%s, 0x%016x>", addr, hash);
	}
}
